<template>
  <div class="app-container">
      <div class="draft" style="height: 100%"  v-show="!showForm">
          <div>
              <!-- 列表 -->
               <div style="marginBottom: 20px">
                    <el-input v-model="searchText" placeholder="请输入要查询的任务名称" size="small" style="width: 200px">
                    </el-input>
                    <el-button style="marginLeft: 10px" type="primary" size="small" @click="searchChange">搜索</el-button>
                    <el-button style="marginLeft: 10px"  size="small" @click="reset">重置</el-button>
                    <div style="float: right">
                        <el-button size="small" @click="multiDel" :disabled="selectionLength===0">批量删除</el-button>
                    </div>
                </div>
                <el-table ref="multipleTable" :data="tableData" stripe style="width: 100%; marginBottom: 20px" size="small"
                    @selection-change="handleSelectionChange" v-loading="tableLoading" class="tableInfo" row-key="formId">
                    <el-table-column type="selection" width="80" align="center" :reserve-selection="true">
                    </el-table-column>
                    <el-table-column label="序号" width="80" align="center">
                        <template slot-scope="scope">
                        <span>{{
                            scope.$index + (page.pageNo - 1) * page.pageSize + 1
                        }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="formName" label="任务名称" align="center">
                    </el-table-column>
                    <el-table-column prop="processModelName" label="所属流程" align="center">
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" align="center">
                        <template slot-scope="scope">{{
                        getDateTime(scope.row.createTime)
                        }}</template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope"> <!-- 关联流程之后 才有发起审批 -->
                            <el-button size="small" type="text" @click="approvalData(scope.row)" v-show="scope.row.processModelName">发起审批</el-button>
                            <el-button size="small" type="text" @click="viewData(scope.row)">查看</el-button>
                            <el-button size="small" type="text" @click="editData(scope.row)">编辑</el-button>
                            <el-button size="small" type="text" style="color: red" @click="delData(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination background :layout="layout" :total="pageTotal" :page-size="page.pageSize" :page-sizes="pageSizes"
                :current-page="page.pageNo" style="float: right;marginBottom: 20px" @size-change="sizeChange" @current-change="currentChange">
                </el-pagination>
          </div>
      </div>
      <div v-show="showForm">
        <!-- <el-dialog :title="title" :visible.sync="dialogVisible" :top="dialogTop" :width="dialogWidth"> -->
        <div style="marginBottom:20px;">
            <span style="fontSize:20px;">{{title}}</span>
            <el-button type="primary" @click="()=>{showForm = false}" style="marginLeft:10px;float:right;" size="small">返回
            </el-button>
        </div>
        <div style="display:flex;justifyContent:center;">
            <parser :form-conf="formConfData" :status="status" :originData="originData" v-if="showForm"  @submit="submitForm"
            @save="saveForm" @cancel="cancelForm" style="width:80%;" />
        </div>
        <!-- </el-dialog> -->
     </div>
  </div>
</template>


<script>

import { createProcessInstance } from "@/api/bpm/processInstance"
import { getDraft, getDataOneId, delMulti} from '@/api/custom/message'
import { deletedata } from "@/api/custom/formPoster";
import Parser from '../formdesign/components/parser'
 import { updata } from "@/api/custom/formPoster";
const arrTypes = ['cascader', 'checkbox', 'time-range', 'date-range'];
const basicTypes = ['number', 'color', 'rate', 'date', 'time', 'password', 'textArea', 'input',
    'slider', 'select', 'radio', 'numbers'
]; //从数据库中获取值无需处理
export default {
     components: {
      Parser
    },
    data() {
        return {
            tableLoading: false,
            showForm: false, //表单新增、编辑、查看页面
            searchText: "", //关键字搜索
            tableData: [],
            layout: "prev, pager, next,sizes,jumper", //分页显示布局
            pageSizes: [10, 20, 30, 50], //分页显示每页条数选择
            pageTotal: 3,
            page: {
                pageNo: 1, // 当前页数
                pageSize: 10, // 每页显示多少条
            },
            fields: [],
            fieldData: [], //字段
            fieldKey: {}, //字段键值对
            originData: {},
            formConfData: {},
            tagIcons: [],
            multipleSelection: [],
            tableName: '',
            processModelName: '' //是否关联流程
        }
    },
    mounted() {
      this.getList();
    },
    computed: {
      selectionLength() {
        return this.multipleSelection.length
      }
    },
    methods: {
      //取消按钮
      cancelForm(){
        this.showForm=false
      },
       //数据格式化成对应数据库存储类型
      getFormatValue(data, tag, format) {
        if (arrTypes.includes(tag)) { //组件数据类型为数组
          return data.toString()
        }
        if (tag === 'upload') {
          return JSON.stringify(data)
        }
        if ((format === 'int' || format === 'double'|| format === 'decimal') && !Number.isNaN(data)) { //数据库存储类型为int或double，但组件数据类型为字符串
          if(tag === "number"){
            return data!==''?data:''
          }
          return data!==''?Number(data):''
        }
        if (format === 'varchar') {
          return data.toString()
        }
        return data
      },
      // 保存按钮
      saveForm(data) {
        if (!data) {
          return;
        }
        let fields = []
        this.fieldData.map((item, index) => {
          if (data[item.value] !== undefined && data[item.value] !== null) {
            let value = this.getFormatValue(data[item.value], this.tagIcons[index], item.format)
            fields.push({
              name: item.value,
              type: item.format,
              value: value
            })
          }
        })
        const params = {
          tableName: this.tableName,
          dataId: this.formRecordId,   //formRecordId
          data: fields
        }
        updata(params).then((res) => {
          if(res.code === 0){
             this.showForm=false
             this.getList();
          }
        })
      },
      // 提交按钮
      submitForm(data) {
        if (!data) {
          return;
        }
        // updata  dataType: '2', 如果关联流程 再掉 creat 
        let fields = []
        this.fieldData.map((item, index) => {
          if (data[item.value] !== undefined && data[item.value] !== null) {
            let value = this.getFormatValue(data[item.value], this.tagIcons[index], item.format)
            fields.push({
              name: item.value,
              type: item.format,
              value: value
            })
          }
        })
        const params = {
          tableName: this.tableName,
          dataType: '2',
          data: fields,
          dataId: this.formRecordId,   //formRecordId
        }
        this.variables = data
        updata(params).then((res) => {
          if(res.code === 0){
              if(this.processModelName){ //关联流程
                  const data = {
                    formId: this.formId,
                    formRecordId: this.formRecordId,
                    variables: this.variables
                  }
                  createProcessInstance(data).then((res) => {
                    this.$message.success('提交成功')
                    this.showForm=false
                    this.getList();
                  })
              }else{ // 没有关联流程
                  this.$message.success('提交成功')
                  this.showForm=false
                  this.getList();
              }
          }
        })
      },
      //获取表单数据
      getList() {
        this.tableLoading = true;
        let params = {
          ...this.page,
          formName: this.searchText,
        };
        getDraft(params)
          .then((res) => {
            if (res.code === 0) {
              this.tableData = res.data.list;
              this.pageTotal = res.data.total;
              this.tableLoading = false;
              this.tableName = JSON.parse(res.data.formJsonData).tableName
            }
          })
          .catch((e) => {
            this.tableLoading = false;
          });
        },
       getTagIcons(data) {
        if (data.length === 0) return
        data.filter((item) => {
          return item.__config__.tag !== 'TitleLine'
        }).map((item) => {
          if (item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse' || item.__config__.tag === 'el-card') {
            let tem = item.__config__.children.map((c) => {
              this.getTagIcons(c.__config__.children)
            })
          } else {
            let tag = item.__config__.tagIcon
            let options = []
            if (tag === 'switch') {
              options = [item['active-value'], item['inactive-value']]
            } else if (['select', 'radio', 'checkbox', ].includes(tag)) {
              if (item.dataType === 'static') {
                options = item.options
              } else if (item.dataType === 'dictionary' && item.dictName !== '') {
                getDictData({
                  dictType: item.dictName
                }).then((res) => {
                  if (res.code === 0) {
                    res.data.forEach((item) => {
                      options.push({
                        label: item.label,
                        value: item.label
                      })
                    })
                  }
                }).catch(e => {
                  console.log(e)
                })
              } else if (item.dataType === 'datasource' && item.tableName !== '' && item.fieldName !== '') {
                getColumnData({
                  tableName: item.tableName,
                  column: item.fieldName,
                }).then((res) => {
                  if (res.code === 0) {
                    res.data.forEach((item) => {
                      options.push({
                        label: item,
                        value: item
                      })
                    })
                  }
                }).catch(e => console.log(e))
              }
            } else if (tag === 'cascader') {
              options = item.options

            }
            this.tagIcons.push({
              tag: tag,
              option: options
            })

            console.log(options)
            // this.tagIcons.push({
            //   tag: tag,
            //   option: options
            // })
          }
        })
      },
        //修改数据
        editData(row) {
            this.formId = row.formId
            this.formRecordId = row.formRecordId
            this.processModelName = row.processModelName
            this.status = 'edit'
            this.title = '编辑'
            this.formConfData = JSON.parse(row.formJsonUser)
            this.getTagIcons(this.formConfData.fields)
            this.fields = JSON.parse(row.formJsonData).data
            this.tableName = JSON.parse(row.formJsonData).tableName
            let columns = []
            this.fieldData = this.fields.map((item, index) => {
              this.fieldKey[item.name] = item.desc
              columns.push({
                columnName: item.desc,
                hide: false
              })
              return {
                name: item.desc,
                value: item.name,
                format: item.format,
                tag: this.tagIcons[index].tag,
                options: this.tagIcons[index].option
              }
            })
            this.current = row.id
            const data = {
                id: row.formRecordId,
                tableName: JSON.parse(row.formJsonData).tableName
            }
            getDataOneId(data).then((res) => {
                if(res.code == 0){
                    this.fieldData.map((item, index) => {
                        this.originData[item.value] = this.setFormatValue(res.data[item.value], item.format, item.tag, item.options)
                    })
                    this.showForm = true
                }
            })
        },
        //查看数据
        viewData(row) {
            this.status = 'view'
            this.title = '查看'
            this.formConfData = JSON.parse(row.formJsonUser)
            this.getTagIcons(this.formConfData.fields)
            this.fields = JSON.parse(row.formJsonData).data
            let columns = []
            this.fieldData = this.fields.map((item, index) => {
              this.fieldKey[item.name] = item.desc
              columns.push({
                columnName: item.desc,
                hide: false
              })
              return {
                name: item.desc,
                value: item.name,
                format: item.format,
                tag: this.tagIcons[index].tag,
                options: this.tagIcons[index].option
              }
            })
            const data = {
                id: row.formRecordId,
                tableName: JSON.parse(row.formJsonData).tableName
            }
            getDataOneId(data).then((res) => {
                if(res.code == 0){
                     this.fieldData.map((item, index) => {
                        this.originData[item.value] = this.setFormatValue(res.data[item.value], item.format, item.tag, item.options)
                    })
                    this.showForm = true
                }
            })
        },
    //将数据库存储类型转为组件数据类型
      setFormatValue(data, format, tag, options) {
        if (!data) { //空数据
          return data
        }
        if (format === 'datetime') {
          return this.getDateTime(data)
        }
        if (tag === 'upload') {
          if (this.isJson(data)) {
            return JSON.parse(data)
          } else {
            return []
          }
        }
        if (basicTypes.includes(tag)) {
          // if (format === 'double' && tag!=='number') {
          //   return data.toString()
          // } else {
          //   return data
          // }
          return data
        }
        if (tag === 'time-range' || tag === 'date-range' || tag === 'checkbox') {
          return data.split(',')
        }
        if (tag === 'switch') {
          if (typeof (options[0]) === 'number') {
            return Number(data)
          } else if (typeof (options[0]) === 'boolean') {
            return data === 'true' ? true : false
          } else {
            return data
          }
        }
        if (tag === 'radio' || tag === 'select') {
          if (typeof (options[0].value) === 'number') {
            return Number(data)
          } else if (typeof (options[0].value) === 'boolean') {
            return data === 'true' ? true : false
          } else {
            return data
          }
        }
        if (tag === 'cascader') {
          let keys = data.split(',')
          if (typeof (options[0].value) === 'number') {
            return keys.map((item) => {
              return Number(item)
            })
          } else if (typeof (options[0].value) === 'boolean') {
            return keys.map((item) => {
              return data === 'true' ? true : false
            })
          }
          return keys
        }
        return data
      },
        //时间戳转日期时间
        getDateTime(time) {
            if (!time) return ''
            let date = new Date(time)
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            let hour = date.getHours()
            let minute = date.getMinutes()
            let second = date.getSeconds()
            return `${year}-${month<10?'0':''}${month}-${day<10?'0':''}${day} ${hour<10?'0':''}${hour}:${minute<10?'0':''}${minute}:${second<10?'0':''}${second}`
        },
          //搜索
        searchChange() {
            this.page.pageNo = 1;
            this.getList();
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
            this.page.pageNo = 1;
            this.getList();
        },
        currentChange(current) {
            this.page.pageNo = current;
            this.getList();
        },
        reset() {
            this.searchText = '';
            this.searchChange();
        },
        approvalData(row) {  //发起审批
           const data = {
                id: row.formRecordId,
                tableName: JSON.parse(row.formJsonData).tableName
            }
             getDataOneId(data).then((res) => {
                if(res.code == 0){
                    const fields = JSON.parse(row.formJsonData).data
                    let arr = []
                    fields && fields.map((_) => {
                        return arr.push(_.name)
                    })
                    let obj = {}
                    arr && arr.map((_) => {
                        return obj[_] = res.data[_]
                    })
                    createProcessInstance({
                        formId: row.formId,
                        formRecordId: row.formRecordId,
                        variables: obj
                    }).then(res => {
                        this.$message.success('发起审批成功 ')
                        this.getList()
                    })
                }
             })
            
        },
        delData(row) { //删除
            let ids = []
            ids.push(row.formRecordId)
            const that = this;
            this.$modal.confirm('是否删除该草稿！').then(function() {
                deletedata({
                    tableName: JSON.parse(row.formJsonData).tableName,
                    ids: ids.join(',')
                }).then(response => {
                    that.$modal.msgSuccess("删除成功");
                    that.getList();
                })
            }).catch(() => {});
        },
        //多选
    handleSelectionChange(val) {
        this.multipleSelection = val
    },
        //批量删除数据
    multiDel() {
        let data = []
        this.multipleSelection.map((item) => {
            data.push({id: item.formRecordId,tableName:JSON.parse(item.formJsonData).tableName})
        })
        delMulti(data).then((res) => {
            if (res.code === 0) {
                this.$message.success('删除成功')
                this.multipleSelection = []
                this.tableLoading = true
                this.page.pageNo = 1
                this.$refs.multipleTable.clearSelection()
                this.getList()
            }
        })
      },
    }

}
</script>

<style lang="scss" scoped>
    .draft{

    }
</style>